package utils

import (
	"fmt"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"net"
	"strings"
)

// PortCheck 检查端口是否可用，可用-true 不可用-false
func PortCheck(host string, port int) bool {
	l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))

	if err != nil {
		return false
	}
	defer l.Close()
	return true
}

// GetRemoteAddr 获取远程IP
func GetRemoteAddr(rc *app.RequestContext) string {
	ip, _, _ := net.SplitHostPort(rc.RemoteAddr().String())
	if ip == "" || ip == "127.0.0.1" || strings.HasPrefix(ip, "192.168.") {
		ip = string(rc.GetHeader("X-Real-IP"))
		hlog.Infof("RemoteAddr(X-Real-IP)：%s", ip)
	}
	if ip == "" || ip == "127.0.0.1" || strings.HasPrefix(ip, "192.168.") {
		ip = string(rc.GetHeader("X-Forwarded-For"))
		hlog.Infof("RemoteAddr(X-Forwarded-For)：%s", ip)
		if len(ip) > 0 {
			ip = strings.Trim(strings.Split(ip, ",")[0], " ")
		}
	}
	if ip == "" {
		ip = "127.0.0.1"
	}

	return ip
}
